package com.zhou.kotlin_car_data_list.ui

import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.databinding.DataBindingUtil
import com.zhou.kotlin_car_data_list.R
import com.zhou.kotlin_car_data_list.adapter.ModelCarListAdapter
import com.zhou.kotlin_car_data_list.bean.Model
import com.zhou.kotlin_car_data_list.bean.ModelListBean
import com.zhou.kotlin_car_data_list.bean.ResultBean
import com.zhou.kotlin_car_data_list.databinding.ActivityModelCarListBinding
import com.zhou.kotlin_car_data_list.utils.CarApi
import com.zhou.kotlin_car_data_list.utils.RetrofitUtils
import retrofit2.Call
import retrofit2.Response

class ModelCarListActivity : AppCompatActivity() {

    val binding: ActivityModelCarListBinding by lazy {
        DataBindingUtil.setContentView(this, R.layout.activity_model_car_list)
    }

    val mData: MutableList<Model> = mutableListOf<Model>()
    val mAdapter : ModelCarListAdapter by lazy {
        ModelCarListAdapter(this, mData)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val brandResultBean = intent.getParcelableExtra("brandBean") as? ResultBean
        binding.title = brandResultBean?.name
        binding.modelCarListAdapter = mAdapter
        brandResultBean?.id?.let { loadDatas(it) }
    }

    private fun loadDatas(id: String) {
        val api = RetrofitUtils.getApi(CarApi.baseUrl, CarApi::class.java)
        val call = id?.let { api.getModelList(CarApi.key, it) }
        call?.enqueue(object : retrofit2.Callback<ModelListBean> {
            override fun onResponse(call: Call<ModelListBean>, response: Response<ModelListBean>) {
                response.body()?.result?.let {
                    mData.addAll(it)
                    mAdapter.notifyDataSetChanged()
                }
            }

            override fun onFailure(call: Call<ModelListBean>, t: Throwable) {

            }

        })
    }
}